package a05_双指针法;

import java.util.Arrays;

/**
 * <p>
 * a03_翻转字符串里的单词复习3
 * </p>
 *
 * @author flyduck
 * @since 2024/12/26
 */
public class a04_翻转字符串里的单词复习3 {

    public static void main(String[] args) {
        a04_翻转字符串里的单词复习3 test = new a04_翻转字符串里的单词复习3();
        System.out.println(test.reverseWords("the sky is blue"));
    }

    public String reverseWords(String s) {
        char[] oldChars = s.toCharArray();
        char[] newChars = removeAllSpaces(oldChars);
        reverse(newChars,0,newChars.length - 1);
        reverseEachWord(newChars);
        return new String(newChars);
    }

    private void reverseEachWord(char[] chars) {
        int leftIdx = 0;
        int rightIdx = 0;
        while (rightIdx < chars.length) {
            if(rightIdx == chars.length - 1 || chars[rightIdx+1] == ' '){
                reverse(chars, leftIdx, rightIdx);
                rightIdx = rightIdx + 2;
                leftIdx = rightIdx;
            }else {
                rightIdx++;
            }
        }

    }

    private void reverse(char[] chars, int leftIdx, int rightIdx) {
        while (leftIdx < rightIdx){
            char temp = chars[leftIdx];
            chars[leftIdx] = chars[rightIdx];
            chars[rightIdx] = temp;
            leftIdx++;
            rightIdx--;
        }
    }

    private char[] removeAllSpaces(char[] chars) {
        int slowIdx = 0;
        int fastIdx = 0;
        while (fastIdx < chars.length){
            if(chars[fastIdx] != ' '){
                if(slowIdx != 0){
                    chars[slowIdx] = ' ';
                    slowIdx++;
                }
                while (fastIdx < chars.length && chars[fastIdx] != ' ') {
                    chars[slowIdx] = chars[fastIdx];
                    slowIdx++;
                    fastIdx++;
                }
            }else {
                fastIdx++;
            }
        }
        return Arrays.copyOfRange(chars, 0, slowIdx);
    }
}
